package com.ryenlii.datatrans.adapter;

import java.util.ArrayList;
import java.util.List;

public class RequestFuture {
    private final List<RequestFutureListener> requestFutureListenerList;

    public RequestFuture() {
        this.requestFutureListenerList = new ArrayList<>();
    }

    public void onComplete(String message) {
        // 假设只执行成功的方法
        fireSuccess(message);
    }

    private void fireSuccess(String message) {
        // 假设只执行成功的方法
        requestFutureListenerList.forEach(requestFutureListener -> {
            requestFutureListener.onSuccess(message);
        });
    }

    void addListener(RequestFutureListener requestFutureListener) {
        requestFutureListenerList.add(requestFutureListener);
    }

    /**
     * 相当于给RequestFuture addListener
     */
    public RequestFuture compose(ResponseHandleAdapter responseHandleAdapter) {
        // 这里实现将结果传播出去的关键代码，执行完各个responseHandleAdapter后，
        // 链式的执行调用compose方法，调用compose方法会添加一个listener
        final RequestFuture future = new RequestFuture();
        addListener(new RequestFutureListener() {
            @Override
            public void onSuccess(String s) {
                // 交回给各个请求处理类处理
                responseHandleAdapter.onSuccess(s, future);
            }

            @Override
            public void onFail() {
                // 暂时不处理
            }
        });
        return future;
    }

}